import modelExtend from 'dva-model-extend'
import * as statisticsOfDialogueService from './services/statisticsOfDialogue'
import * as employeeService from "../employee/services/employees"
import * as dictionaryService from 'services/dictionary'
import * as departmentService from '../department/services/departments'
import {pageModel} from 'utils/model'

const {query, queryStatisticalDiagram} = statisticsOfDialogueService

export default modelExtend(pageModel, {
  namespace: 'statisticsOfDialogue',
  state: {
    condition: 'wxId',  //条件搜索字段
    empList: [],
    departments: [],
    dataOfDiagram: [],
    adAcquireType: [],
    tabsKey: 'table_form', //tabs
    start: null,
    end: null,
    filter: {},
  },
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen((location) => {
        if (location.pathname === '/statisticsOfDialogue') {
          const payload = location.query || {current: 1, size: 10}
          dispatch({
            type: 'query',
            payload,
          })
          dispatch({
            type: 'queryStatisticalDiagram',
            payload,
          })
          dispatch({
            type: "init",
          })
        }
      })
    },
  },
  effects: {
    * queryStatisticalDiagram ({payload = {}}, {call, put}) {
      const response = yield call(queryStatisticalDiagram, payload)
      const {data} = response
      if (response && data) {
        yield put({
          type: 'updateState',
          payload: {
            dataOfDiagram: data.records,
          },
        })
      }
    },

    * query ({payload = {}}, {call, put}) {
      const response = yield call(query, payload)
      const {data} = response
      if (response && data) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.records ? data.records : data,
            pagination: {
              current: Number(payload.current) || 1,
              pageSize: Number(payload.size) || 10,
              total: data.total,
            },
          },
        })
      }
      console.log(payload)
    },

    * init ({payload = {}}, {call, put}) {
      const adAcquireTypeResp = yield call(dictionaryService.queryBySn, { sn: 'customer_channel' })
      const deptResp = yield call(departmentService.query)
      yield put({
        type: 'updateState', payload: {
          adAcquireType: adAcquireTypeResp.data,
          departments: deptResp.data,
        },
      })
    },

    * searchEmp ({payload = {}}, {call, put}) {
      const response = yield call(employeeService.searchEmp, payload)
      const {data} = response
      if (response && data) {
        yield put({
          type: 'updateState',
          payload: {
            empList: data,
          },
        })
      }
    },
  },

  reducers: {
    updateCondition (state, {payload}) {
      return {...state, ...payload}
    },

    updateTabsKey (state, {payload}) {
      return {...state, ...payload}
    },
  },
})
